package com.authManager.web.interceptor;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * 说明：【日志】
 * 
 * @author: xkq
 * @Package com.hy.admin.interceptor
 * @Description: TODO(用一句话描述该文件做什么)
 * @author xkq
 * @date 2018年4月3日
 */
@Component
public class LogInterceptor implements HandlerInterceptor {
	private static final Logger log = LoggerFactory.getLogger(LogInterceptor.class);

	public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
		// 在整个请求结束之后被调用，也就是在DispatcherServlet 渲染了对应的视图之后执行，主要是用于进行资源清理工作
	}

	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
			throws Exception {
		// 请求处理之后进行调用，但是在视图被渲染之前，即Controller方法调用之后
	}

	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object) throws Exception {
		if (object instanceof HandlerMethod) {
			Map<String, String[]> params = request.getParameterMap();
			String queryString = "";
			if (!params.isEmpty()) {
				for (String key : params.keySet()) {
					String[] values = params.get(key);
					for (int i = 0; i < values.length; i++) {
						String value = values[i];
						queryString += " " + key + "=" + value + " & ";
					}
				}
				// 去掉最后一个空格
				queryString = queryString.substring(0, queryString.length() - 1);
			}
			log.info("地址是：" + request.getRequestURL() + " 参数是：{ " + queryString + " }");
		}
		return true;
	}
}